package com.kaluli.project.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.log4j.Logger;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

public class HttpUtils {

	private static Logger log = Logger.getLogger(HttpUtils.class);

	private static final String[] A_RIGION = { "内蒙古", "广西", "宁夏", "新疆", "西藏" };
	
	private static final String[] CHANG_RIGION = { "浙江", "江苏", "浙江省", "江苏省"};

	private static final String[] A_RIGION_ATTR = { "内蒙古自治区", "广西壮族自治区", "宁夏回族自治区", "新疆维吾尔自治区", "西藏自治区" };


	public static String post(String u) throws Exception {
		log.info("post请求参数:url=" + u );
		URL url = new URL(u);

		// 打开restful链接
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();

		// 提交模式
		conn.setRequestMethod("POST");// POST GET PUT DELETE
		conn.setRequestProperty("Accept-Charset", "UTF-8");
		// 设置访问提交模式，表单提交
		conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
//		conn.setRequestProperty("Charset", "UTF-8");
//		conn.setRequestProperty("Content-Type", "text/html,charset=utf-8");
		conn.setConnectTimeout(10000);// 连接超时 单位毫秒
		// conn.setReadTimeout(2000);//读取超时 单位毫秒
		conn.setReadTimeout(30000);
		conn.setDoOutput(true);// 是否输入参数


		InputStream inStream = conn.getInputStream();
		byte[] returnBytes = new byte[inStream.available()];
		inStream.read(returnBytes, 0, inStream.available());

		return new String(returnBytes, "utf-8");
		// System.out.println(new String(bypes, "gbk"));
	}

	public static void main(String s[]) {
		String param = "{orderId:'123123123',orderDate:'2016-1-5 12:12:12',customerId: '1000000202',packingMaterial:'纸盒',electriccode:'1000000202',notes:'test',deliveryCode:'',orderType:'1',tpl:'1000823',entInboundId: '1000000202',cbepcomcode:'1000000202',warehouseId:'1',goodList:[{goodId:'4901301230829',amount: 1,price: '10.2'}],recipient:{name:'张贻之',receiveType:'1',receiveNo:'310101198007130416',mobilePhone:'13901899768',phone:'123123123',country:'中国',province:'上海',city:'上海',district:'普陀区',address:'上海 宜山路 300号1103室',postCode:'200333'}}";
//		String test = "{'name':'\u6881\u57fa','postcode':'530000','province':'\u5e7f\u897f','city':'\u5357\u5b81','area':'\u5174\u5b81\u533a','mobile':'18697994321','region':'\u5e7f\u897f \u5357\u5b81 \u5174\u5b81\u533a ','street':'\u9752\u4e91\u8857\u60a6\u835f\u5e7f\u573aC\u5ea7\u8d1f\u4e00\u697cF29','identity_number':'45273019871008261X'}";
		String test = "{'name':'\u5d14\u4e00','postcode':'222222','province':'\u9655\u897f','city':'\u897f\u5b89\u5e02','area':'\u96c1\u5854\u533a','mobile':'18729247841','region':'\u9655\u897f \u897f\u5b89\u5e02 \u96c1\u5854\u533a ','street':'\u6731\u96c0\u5927\u8857\u5357\u6bb5\u534e\u57ce\u4e07\u8c61\u4e8c\u671f','identity_number':'222401198408182133'}";
		
		try {
			JSONObject responseObj = JSON.parseObject(test);
			System.out.println(test);
			String region = responseObj.getString("region");
			System.out.println(fixAddress(region));
			System.out.println(fixProvince(responseObj.getString("province")));
			
			String province = "上海";
			String logisticsCode="";
			System.out.println(CheckProvince(province));
			if(HttpUtils.CheckProvince(province)){
				logisticsCode = "TT";
			}else{
				logisticsCode = "YUNDA";
			}
			System.out.println(logisticsCode);
			

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 发送POST请求
	 *
	 * @param url
	 *            目的地址
	 * @param parameters
	 *            请求参数，Map类型。
	 * @return 远程响应结果
	 */
	public static String sendPost(String url, Map<String, String> parameters) {
		String result = "";// 返回的结果
		BufferedReader in = null;// 读取响应输入流
		PrintWriter out = null;
		StringBuffer sb = new StringBuffer();// 处理请求参数
		String params = "";// 编码之后的参数
		try {
			// 编码请求参数
			if (parameters.size() == 1) {
				for (String name : parameters.keySet()) {
					sb.append(name).append("=").append(
							java.net.URLEncoder.encode(parameters.get(name),
									"UTF-8"));
				}
				params = sb.toString();
			} else {
				for (String name : parameters.keySet()) {
					sb.append(name).append("=").append(
							java.net.URLEncoder.encode(parameters.get(name),
									"UTF-8")).append("&");
				}
				String temp_params = sb.toString();
				params = temp_params.substring(0, temp_params.length() - 1);
			}
			// 创建URL对象
			java.net.URL connURL = new java.net.URL(url);
			// 打开URL连接
			java.net.HttpURLConnection httpConn = (java.net.HttpURLConnection) connURL
					.openConnection();
			// 设置通用属性
			httpConn.setRequestProperty("Accept", "*/*");
			httpConn.setRequestProperty("Connection", "Keep-Alive");
			httpConn.setRequestProperty("User-Agent",
					"Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");
			// 设置POST方式
			httpConn.setDoInput(true);
			httpConn.setDoOutput(true);
			// 获取HttpURLConnection对象对应的输出流
			out = new PrintWriter(httpConn.getOutputStream());
			// 发送请求参数
			out.write(params);
			// flush输出流的缓冲
			out.flush();
			// 定义BufferedReader输入流来读取URL的响应，设置编码方式
			in = new BufferedReader(new InputStreamReader(httpConn
					.getInputStream(), "UTF-8"));
			String line;
			// 读取返回的内容
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		return result;
	}

	public static String fixAddress(String param) {

		String[] regionArray = param.split(" ");
		StringBuffer sb = new StringBuffer();
		int i = 0;
		for (String p : regionArray) {
			if (i == 0 && fixMdu(p)) {
				if (p.indexOf("市") < 0) {
					sb.append(p).append("市").append(" ");
				}
			} else if (i == 0 && !fixZzu(p)) {
				if (p.indexOf("省") < 0) {
					sb.append(p).append("省").append(" ");
				}
			} else if (i == 0) {
				p = addAttr(p);
				sb.append(p).append(" ");
			}

			if (i == 1) {
				if (p.indexOf("市") < 0) {
					sb.append(p).append("市").append(" ");
				}else{
					sb.append(p).append(" ");
				}
			}

			if (i == 2) {
				sb.append(p).append(" ");
			}
			i++;
		}
		return sb.toString();
	}

	public static String fixProvince(String param) {

		StringBuffer sb = new StringBuffer();
		sb.append(param);
		if (fixMdu(param)) {
			if (param.indexOf("市") < 0) {
				sb.append("市");
			}
		} else if (fixZzu(param)) {
			return addAttr(param);
		} else {
			if (param.indexOf("省") < 0) {
				sb.append("省");
			}
		}

		return sb.toString();
	}

	public static String fixCity(String param) {

		StringBuffer sb = new StringBuffer();
		sb.append(param);
		if (param.indexOf("市") < 0) {
			sb.append("市");
		}
		return sb.toString();
	}

	private static boolean fixMdu(String mdu) {
		String[] mdus = { "北京", "上海", "天津", "重庆" };
		boolean flag = false;
		for (String m : mdus) {
			if (m.equals(mdu)) {
				flag = true;
				break;
			}
		}
		return flag;
	}
	
	

	private static boolean fixZzu(String zzu) {
		boolean flag = false;

		for (String z : A_RIGION) {
			if (z.equals(zzu)) {
				flag = true;
				break;
			}
		}

		return flag;
	}
	
	public static boolean CheckProvince(String zzu) {
		boolean flag = false;

		for (String z : CHANG_RIGION) {
			if (z.equals(zzu)) {
				flag = true;
				break;
			}
		}

		return flag;
	}

	private static String addAttr(String region) {

		for (int i = 0; i < A_RIGION.length; i++) {
			if (region.equals(A_RIGION[i])) {
				region = A_RIGION_ATTR[i];
			}
		}

		return region;
	}
	

}

